package com.sskj.ffex;

import android.content.pm.ApplicationInfo;
import android.os.Handler;
import android.os.Looper;
import android.support.multidex.MultiDexApplication;
import android.util.Log;

import com.bulong.rudeness.RudenessScreenHelper;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.DBCookieStore;
import com.lzy.okgo.https.HttpsUtils;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;
import com.shizhefei.mvc.MVCCoolHelper;
import com.sskj.ffex.common.AppManager;
import com.sskj.ffex.common.BaseActivityLifecycleCallbacks;
import com.sskj.ffex.common.Cockroach;
import com.sskj.ffex.common.Constants;
import com.sskj.ffex.mvchelper.LoadViewFactory;
import com.sskj.ffex.utils.LanguageUtil;
import com.sskj.ffex.utils.SPUtils;
import com.sskj.ffex.v.activity.MainActivity;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.zxy.recovery.core.Recovery;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;


/**
 * Created by Lee on 2018/1/25 0025.
 */

public class MyAppLication extends MultiDexApplication {

    public static MyAppLication getApplication() {
        return mApplication;
    }


    private static MyAppLication mApplication;


    @Override
    public void onCreate() {
        super.onCreate();
        mApplication = this;
        new RudenessScreenHelper(this, 750).activate(); //初始化百分比布局
        registerActivityLifecycleCallbacks(new BaseActivityLifecycleCallbacks());
        initOkgoHttp();
        if (!isDebug()){
            Cockroach.install((thread, throwable) -> new Handler(Looper.getMainLooper()).post(() -> {
                try {
                    //建议使用下面方式在控制台打印异常，这样就可以在Error级别看到红色log
                    Log.e("AndroidRuntime", "--->CockroachException:" + thread + "<---", throwable);
                } catch (Throwable e) {

                }
            }));
        }
        MVCCoolHelper.setLoadViewFractory(new LoadViewFactory());
        UMConfigure.init(this, BuildConfig.UMENG_APPKEY, "", UMConfigure.DEVICE_TYPE_PHONE, "");
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);

        if (isDebug()){
            Recovery.getInstance()
                    .debug(true)
                    .recoverInBackground(false)
                    .recoverStack(true)
                    .mainPage(MainActivity.class)
                    .recoverEnabled(true)
                    .callback(null)
                    .silent(false, Recovery.SilentMode.RECOVER_ACTIVITY_STACK)
                    .init(this);
        }

        LanguageUtil.changeAppLanguage(this, LanguageUtil.getAppLocale(this), true);

    }

    public void initOkgoHttp() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        HttpsUtils.SSLParams sslSocketFactory = HttpsUtils.getSslSocketFactory();

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        loggingInterceptor.setColorLevel(Level.INFO);
        builder.addInterceptor(loggingInterceptor);
//        builder.cookieJar(new CookieJarImpl(new DBCookieStore(this)));
//        builder.addInterceptor(loggingInterceptor);
        //信任Https证书
        builder.sslSocketFactory(sslSocketFactory.sSLSocketFactory, sslSocketFactory.trustManager);
        builder.connectTimeout(50, TimeUnit.SECONDS)
                .readTimeout(50, TimeUnit.SECONDS)
                .writeTimeout(50, TimeUnit.SECONDS);
//        .hostnameVerifier(new HostnameVerifier() {
//            @Override
//            public boolean verify(String hostname, SSLSession session) {
//                return true;
//            }
//        });


        HttpHeaders headers = new HttpHeaders();
        headers.put("account", getAccount());    //所有的 header 都 不支持 中文
        headers.put("token", getToken());

        OkGo.getInstance().init(this)//必须调用初始化
                .setOkHttpClient(builder.build())//必须设置OkHttpClient
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .addCommonHeaders(headers)
                .setRetryCount(0);
        //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
//                .addCommonHeaders(headers)                      //全局公共头
//                .addCommonParams(params);
    }

    public static String getMobile() {
        return (String) SPUtils.get(mApplication, Constants.SP_MOBILE, "");
    }

    public static String getToken() {
        return (String) SPUtils.get(mApplication, Constants.SP_TOKEN, "");
    }

    public static String getAccount() {
        return (String) SPUtils.get(mApplication, Constants.SP_ACCOUNT, "");
    }

    public static boolean isLogin() {
        return (boolean) SPUtils.get(MyAppLication.getApplication(), Constants.SP_LOGIN_STATUS, false);
    }

    public static boolean isShop() {
        return (boolean) SPUtils.get(MyAppLication.getApplication(), Constants.SP_IS_SHOP, false);
    }

    public static String getName() {
        return (String) SPUtils.get(MyAppLication.getApplication(), Constants.SP_REALNAME, "");
    }

    public static String getIdCard() {
        return (String) SPUtils.get(MyAppLication.getApplication(), Constants.SP_IDCORD, "");
    }

    public static String getJGCode() {
        return (String) SPUtils.get(MyAppLication.getApplication(), Constants.SP_JGCODE, "");
    }

    public static String getLANGUAGE() {
        return (String) SPUtils.get(MyAppLication.getApplication(), Constants.LANGUAGE, "zh","zh");
    }

    public static int getGOOGLETYPE() {
        return (int) SPUtils.get(MyAppLication.getApplication(), Constants.GOOGLETYPE, 0);
    }

    public static String getUId() {
        return (String) SPUtils.get(MyAppLication.getApplication(), Constants.SP_UID, "");
    }

    /**
     * 实名初级认证状态 2-审核中 ， 3-已认证， 4-认证失败
     */
    public static int getRealnameStatus() {
        return (int) SPUtils.get(MyAppLication.getApplication(), Constants.SP_REALNAME_STATUS, 0);
    }

    /**
     * 实名高级认证状态 2-审核中 ， 3-已认证， 4-认证失败
     */
    public static int getRealnameStatusHigh() {
        return (int) SPUtils.get(MyAppLication.getApplication(), Constants.SP_REALNAME_STATUS_HIGH, 0);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        Cockroach.uninstall();
    }

    /**
     * 退出应用
     *
     * @param mainActivityClass
     */
    public static void exitApp(Class<MainActivity> mainActivityClass) {
        AppManager.getAppManager().finishAllActivity(mainActivityClass);
    }


    public boolean isDebug(){
        ApplicationInfo info=this.getApplicationInfo();
        return (info.flags&ApplicationInfo.FLAG_DEBUGGABLE)!=0;
    }
}
